import { useAppConfig } from '@vben/hooks';
import { useAccessStore } from '@vben/stores';
import { $t } from '@vben/locales';
interface NavigationItem {
  id: number;
  parent_id: number;
  type: number;
  status: number;
  list_order: number;
  app: string;
  controller: string;
  action: string;
  param: string;
  name: string;
  icon: string;
  remark: string;
}

interface NavigationNode {
  path: string;
  component?: string;
  name?: string;
  status?: number;
  app: string;
  controller: string;
  action: string;
  meta: {
    activePath?: string;
    hideChildrenInMenu?: boolean;
    hideInMenu?: boolean;
    icon: string;
    iframeSrc?: string;
    keepAlive?: boolean;
    param?: string;
    rank?: number;
    roles?: string[];
    showParent?: boolean;
    title: string;
  };
  children?: NavigationNode[];
}

/**
 * 第一个字母大写
 * @param string
 * @returns
 */
export function capitalizeFirstLetter(string: string): string {
  return string.charAt(0).toUpperCase() + string.slice(1);
}

/**
 * 字符串转对象
 * @param queryString
 * @returns
 */
export const queryStringToObject = (
  queryString: string,
): { [key: string]: string } => {
  const params = new URLSearchParams(queryString);
  const result: { [key: string]: string } = {};

  for (const [key, value] of params.entries()) {
    result[key] = value;
  }

  return result;
};

/**
 * 转换驼峰命名法为下划线命名
 * @param str
 * @returns
 */
export const toSnakeCase = (str: string): string => {
  return str.replaceAll(/([a-z])([A-Z])/g, '$1_$2').toLowerCase();
};

/**
 * 创建默认的 NavigationNode
 * @returns NavigationNode
 */
function createDefaultNode(): NavigationNode {
  return {
    app: '',
    controller: '',
    action: '',
    path: '',
    meta: { title: '', icon: '' },
    children: [],
  };
}

/**
 * 将后台返回的菜单数组转为树
 * @param arr
 * @param modulesRoutes
 * @returns
 */
export function convertArrayToNavigationTree(
  arr: NavigationItem[],
  modulesRoutes: any,
): NavigationNode[] {
  const map: { [key: number]: NavigationNode } = {};
  const { baseURL } = useAppConfig(import.meta.env, import.meta.env.PROD);
  const modulesRoutesKeys = Object.keys(modulesRoutes);

  // 筛选有效菜单项
  const array = arr.filter(
    (item) =>
      item.status === 1 ||
      (item.type === 1 && item.parent_id === 0) ||
      (item.type === 0 && item.status === 1) ||
      (item.type === 1 &&
        item.status === 0 &&
        ['detail', 'index'].includes(item.action)),
  );

  // 初始化 map
  array.forEach((item) => {
 
    map[item.id] = {
      ...createDefaultNode(),
      meta: {
       title:$t('page.menu.'+item.name),
        icon:
          item.icon !== '' && item.icon?.startsWith('ri-')
            ? `ri-${item.icon}`
            : `${item.icon ? `fa-${item.icon}` : ''}`,
      },
    };
    
  });



  const tree: NavigationNode[] = [];

  // 构建树结构
  array.forEach((item) => {
    const node = map[item.id] || createDefaultNode();

    if (item.parent_id === 0) {
      const parentPath = `/${item.app}_${item.controller}`
        .toLowerCase()
        .replace('_adminindex', '')
        .replace('_index', '');
      // 根节点
      node.path = parentPath;
      node.meta.rank = item.list_order || 1;
      node.component = 'BasicLayout';
      node.name = capitalizeFirstLetter(
        `${item.app}${item.controller}${item.action}`.replace('index', ''),
      );
      node.app = item.app;
      node.controller = item.controller;
      node.action = item.action;
      node.status = item.status;
      if (item.status === 0) {
        node.meta.hideInMenu = true;
        node.children = [
          {
            app: item.app,
            controller: item.controller,
            action: item.action,
            status: 1,
            path: `/${item.app}/${item.controller}/${item.action}`.toLowerCase(),
            name: `${node.name}Index`.replaceAll('/', ''),
            component:
              `/${item.app}/${item.controller}/${item.action}`.toLowerCase(),
            meta: { title: item.name, icon: '', hideInMenu: true },
          },
        ];
      }
      tree.push(node);
    } else {
      // 子节点
      const parent = map[item.parent_id];
      if (parent) {
        node.path = `/${item.app}/${item.controller}/${item.action}`
          .toLowerCase()
          .replace('/index', '');
        node.component = `${node.path}/index`;
        node.status = item.status;
        node.name = capitalizeFirstLetter(
          `${item.app}${item.controller}${item.action}`.replace('index', ''),
        ).replaceAll('/', '');
        node.app = item.app;
        node.controller = item.controller;
        node.action = item.action;

        if (item.controller === 'Dev' || item.status === 0) {
          node.meta.hideInMenu = true;
        }

        // 如果子菜单没有图标则使用父菜单的图标
        // if (!node.meta.icon) {
        //   node.meta.icon = parent.meta.icon;
        // }

        parent.children = parent.children || [];
        parent.children.push(node);
        if (item.param) {
          const param = queryStringToObject(item.param);
          node.meta.param = item.param;
          let parentPath = `/${item.app}/${item.controller}/:id`.toLowerCase();
          let parentName = capitalizeFirstLetter(
            `${item.app}${item.controller}Detail`,
          );
          if (param.code) {
            node.meta.hideChildrenInMenu = true;
            node.name += capitalizeFirstLetter(param.code || '').replaceAll(
              '/',
              '',
            );
            node.path = `${node.path}/${param.code}`;
            parentPath =
              `/${item.app}/${item.controller}/${param.code}/:code/:id`.toLowerCase();
            parentName = capitalizeFirstLetter(
              `${item.app}${item.controller}${param.code}Detail`,
            );
          }
          if (param.isDetail) {
            // 新增同级菜单
            const detailNode: NavigationNode = {
              ...createDefaultNode(),
              app: item.app,
              controller: item.controller,
              action: item.action,
              path: parentPath,
              name: parentName,
              component: `/${item.app}/${item.controller}/detail`.toLowerCase(),
              meta: {
                title: `${item.name}`,
                icon: '',
                hideInMenu: true,
                activePath: node.path,
                keepAlive: !param.isAdd,  // 新增页不缓存
              },
            };

            // 检查是否存在相同 path 的节点
            const siblings = parent ? parent.children || [] : tree;
            const isDuplicate = siblings.some(
              (sibling) => sibling.path === detailNode.path,
            );

            // 如果不存在相同 path，则新增
            if (!isDuplicate) {
              if (parent) {
                parent.children = siblings; // 确保父节点有 children 数组
                // 将 detailNode 添加到 parent.children 的末尾
                parent.children.push(detailNode);
              } else {
                tree.push(detailNode);
              }
            }
          }
        }
      }
    }
  });


  // 删除只有一个子菜单的节点
  Object.values(map).forEach((node) => {

    if (!modulesRoutesKeys.some((key) => key.includes(node.component || ''))) {
      const accessStore = useAccessStore();
      const path = toSnakeCase(
        `/${node.app}/${node.controller}/${node.action}`,
      );
      const iframeSrc = `${baseURL}${path}?access_token=${accessStore.accessToken}`;
      node.meta.iframeSrc = iframeSrc;
      node.component = 'IFrameView';
    }

    if (node.children && node.children.length === 1) {
      const child = node.children[0];
      if (child && child.status !== 1) {
        node.children = [];
      } else {
        delete child?.meta.iframeSrc;
        delete node?.meta.iframeSrc;
        node.component = 'BasicLayout';
      }
    }
    if (node.children && node.children.length > 1) {
      node.component = 'BasicLayout';
      delete node.meta.iframeSrc;
    }
  });

  return tree;
}
